<template>
	<view class="order-detail-container">
		<view v-if="order" class="order-content">
			<!-- 订单状态 -->
			<view class="status-section">
				<view class="status-icon" :class="getStatusClass(order.status)">
					<text class="status-icon-text">{{ getStatusIcon(order.status) }}</text>
				</view>
				<view class="status-info">
					<text class="status-text">{{ getStatusText(order.status) }}</text>
					<text class="status-desc">{{ getStatusDesc(order.status) }}</text>
				</view>
			</view>

			<!-- 收货地址 -->
			<view class="address-section">
				<view class="section-title">收货信息</view>
				<view v-if="order.shipping_address && order.shipping_address.recipient_name" class="address-info">
					<view class="address-header">
						<text class="recipient-name">{{ order.shipping_address.recipient_name }}</text>
						<text class="phone-number">{{ order.shipping_address.phone_number }}</text>
					</view>
					<view class="address-detail">
						{{ order.shipping_address.province }} {{ order.shipping_address.city }} {{ order.shipping_address.district }} {{ order.shipping_address.detailed_address }}
					</view>
				</view>
				<view v-else class="address-info no-address">
					<view class="no-address-content">
						<text class="no-address-icon">📍</text>
						<text class="no-address-text">此订单创建时未保存收货地址信息</text>
						<text class="no-address-tip">联系客服可获取详细配送信息</text>
					</view>
				</view>
			</view>

			<!-- 商品信息 -->
			<view class="goods-section">
				<view class="section-title">商品信息</view>
				<view class="goods-list">
					<view v-for="(item, index) in order.items" :key="index" class="goods-item">
						<image :src="item.product_image_url" class="goods-image" mode="aspectFill"></image>
						<view class="goods-info">
							<text class="goods-name">{{ item.product_name }}</text>
							<view class="goods-price-qty">
								<text class="goods-price">¥{{ item.price.toFixed(2) }}</text>
								<text class="goods-qty">x{{ item.quantity }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 订单信息 -->
			<view class="order-info-section">
				<view class="section-title">订单信息</view>
				<view class="info-list">
					<view class="info-item">
						<text class="info-label">订单编号</text>
						<text class="info-value">{{ order.order_number }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">下单时间</text>
						<text class="info-value">{{ formatTime(order.created_at) }}</text>
					</view>
					<view v-if="order.payment_time" class="info-item">
						<text class="info-label">支付时间</text>
						<text class="info-value">{{ formatTime(order.payment_time) }}</text>
					</view>
					<view v-if="order.transaction_id" class="info-item">
						<text class="info-label">交易单号</text>
						<text class="info-value">{{ order.transaction_id }}</text>
					</view>
					<view v-if="order.customer_notes" class="info-item">
						<text class="info-label">订单备注</text>
						<text class="info-value">{{ order.customer_notes }}</text>
					</view>
				</view>
			</view>

			<!-- 费用明细 -->
			<view class="price-section">
				<view class="section-title">费用明细</view>
				<view class="price-list">
					<view class="price-item">
						<text class="price-label">商品总价</text>
						<text class="price-value">¥{{ order.total_amount.toFixed(2) }}</text>
					</view>
					<view class="price-item">
						<text class="price-label">配送费</text>
						<text class="price-value">¥{{ order.shipping_fee.toFixed(2) }}</text>
					</view>
					<view class="price-item total-item">
						<text class="price-label">实付款</text>
						<text class="price-value total-price">¥{{ order.payment_amount.toFixed(2) }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-else class="loading-state">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 底部操作按钮 -->
		<view v-if="order" class="action-section">
			<button 
				v-if="order.status === 'pending_payment'" 
				class="action-btn pay-btn"
				@click="goToPay"
			>
				立即支付
			</button>
			<button 
				v-if="order.status === 'pending_payment'" 
				class="action-btn cancel-btn"
				@click="cancelOrder"
			>
				取消订单
			</button>
			<button 
				v-if="order.status === 'processing'" 
				class="action-btn refund-btn"
				@click="requestRefund"
			>
				申请退款
			</button>
			<button 
				v-if="order.status === 'shipped'" 
				class="action-btn confirm-btn"
				@click="confirmReceived"
			>
				确认收货
			</button>
		</view>
	</view>
</template>

<script>
import { get, post, put, showLoading, hideLoading } from '@/utils/request.js'

export default {
	data() {
		return {
			orderId: null,
			order: null
		}
	},
	onLoad(options) {
		this.orderId = options.id;
		this.loadOrderDetail();
	},
	onShow() {
		// 页面显示时刷新订单详情
		if (this.orderId) {
			this.loadOrderDetail();
		}
	},
	methods: {
		// 加载订单详情
		async loadOrderDetail() {
			try {
				showLoading('加载中...');
				const res = await get(`/miniapp/orders/${this.orderId}`);
				this.order = res.data;
			} catch (error) {
				console.error('加载订单详情失败:', error);
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} finally {
				hideLoading();
			}
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				'pending_payment': '待支付',
				'processing': '待发货',
				'shipped': '待收货',
				'completed': '已完成',
				'cancelled': '已取消',
				'refunded': '已退款'
			};
			return statusMap[status] || '未知状态';
		},

		// 获取状态描述
		getStatusDesc(status) {
			const descMap = {
				'pending_payment': '请在15分钟内完成支付',
				'processing': '商家正在准备您的商品',
				'shipped': '商品已发货，请注意查收',
				'completed': '订单已完成，感谢您的购买',
				'cancelled': '订单已取消',
				'refunded': '退款已申请，将在1-3个工作日内到账'
			};
			return descMap[status] || '';
		},

		// 获取状态图标
		getStatusIcon(status) {
			const iconMap = {
				'pending_payment': '💰',
				'processing': '📦',
				'shipped': '🚚',
				'completed': '✅',
				'cancelled': '❌',
				'refunded': '💸'
			};
			return iconMap[status] || '❓';
		},

		// 获取状态样式类
		getStatusClass(status) {
			return `status-${status.replace('_', '-')}`;
		},

		// 格式化时间
		formatTime(timeStr) {
			const date = new Date(timeStr);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hour = String(date.getHours()).padStart(2, '0');
			const minute = String(date.getMinutes()).padStart(2, '0');
			const second = String(date.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
		},

		// 跳转到支付页面
		goToPay() {
			uni.navigateTo({
				url: `/pages/order/payment?orderId=${this.order.id}&orderNumber=${this.order.order_number}&amount=${this.order.payment_amount}`
			});
		},

		// 取消订单
		cancelOrder() {
			uni.showModal({
				title: '确认取消',
				content: '确定要取消这个订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							showLoading('取消中...');
							await put(`/miniapp/orders/${this.order.id}/cancel`, {});
							uni.showToast({
								title: '订单已取消',
								icon: 'success'
							});
							this.loadOrderDetail();
						} catch (error) {
							console.error('取消订单失败:', error);
							uni.showToast({
								title: error.message || '取消失败',
								icon: 'none'
							});
						} finally {
							hideLoading();
						}
					}
				}
			});
		},

		// 申请退款
		requestRefund() {
			uni.showModal({
				title: '申请退款',
				content: '确认要申请退款吗？退款将在1-3个工作日内处理完成，金额将退回到您的支付账户。',
				success: async (res) => {
					if (res.confirm) {
						try {
							showLoading('申请中...');
							await post(`/miniapp/orders/${this.order.id}/refund`, {
								reason: '用户主动申请退款'
							});
							uni.showToast({
								title: '退款申请成功',
								icon: 'success'
							});
							this.loadOrderDetail();
						} catch (error) {
							console.error('申请退款失败:', error);
							uni.showToast({
								title: error.message || '申请失败',
								icon: 'none'
							});
						} finally {
							hideLoading();
						}
					}
				}
			});
		},

		// 确认收货
		confirmReceived() {
			uni.showModal({
				title: '确认收货',
				content: '确认已收到商品吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							showLoading('确认中...');
							// TODO: 后端需要提供确认收货的接口
							// await post(`/miniapp/orders/${this.order.id}/confirm-received`, {}, 'PUT');
							uni.showToast({
								title: '确认收货成功',
								icon: 'success'
							});
							this.loadOrderDetail();
						} catch (error) {
							console.error('确认收货失败:', error);
							uni.showToast({
								title: error.message || '确认失败',
								icon: 'none'
							});
						} finally {
							hideLoading();
						}
					}
				}
			});
		}
	}
}
</script>

<style scoped>
.order-detail-container {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.order-content {
	padding: 20rpx;
}

.status-section {
	background-color: #FFFFFF;
	border-radius: 16rpx;
	padding: 40rpx 30rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
}

.status-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
}

.status-pending-payment {
	background-color: #FFF7E6;
}

.status-processing {
	background-color: #E6F7FF;
}

.status-shipped {
	background-color: #F6FFED;
}

.status-completed {
	background-color: #F5F5F5;
}

.status-cancelled {
	background-color: #FFF2F0;
}

.status-refunded {
	background-color: #FFF7E6;
}

.status-icon-text {
	font-size: 40rpx;
}

.status-info {
	flex: 1;
}

.status-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	display: block;
	margin-bottom: 8rpx;
}

.status-desc {
	font-size: 24rpx;
	color: #666666;
}

.address-section, .goods-section, .order-info-section, .price-section {
	background-color: #FFFFFF;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
}

.address-info {
	padding: 20rpx;
	background-color: #FAFAFA;
	border-radius: 12rpx;
}

.address-header {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
}

.recipient-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #333333;
	margin-right: 20rpx;
}

.phone-number {
	font-size: 28rpx;
	color: #666666;
}

.address-detail {
	font-size: 28rpx;
	color: #666666;
	line-height: 1.4;
}

.goods-list {
	gap: 20rpx;
}

.goods-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #F0F0F0;
}

.goods-item:last-child {
	border-bottom: none;
}

.goods-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
}

.goods-info {
	flex: 1;
}

.goods-name {
	font-size: 28rpx;
	color: #333333;
	margin-bottom: 12rpx;
	display: block;
}

.goods-price-qty {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.goods-price {
	font-size: 32rpx;
	color: #D4AF37;
	font-weight: bold;
}

.goods-qty {
	font-size: 28rpx;
	color: #666666;
}

.info-list, .price-list {
	gap: 16rpx;
}

.info-item, .price-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16rpx 0;
	border-bottom: 1rpx solid #F0F0F0;
}

.info-item:last-child, .price-item:last-child {
	border-bottom: none;
}

.info-label, .price-label {
	font-size: 28rpx;
	color: #666666;
}

.info-value, .price-value {
	font-size: 28rpx;
	color: #333333;
	text-align: right;
	flex: 1;
	margin-left: 20rpx;
}

.total-item .price-label {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.total-price {
	font-size: 36rpx;
	font-weight: bold;
	color: #D4AF37;
}

.loading-state {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 400rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666666;
}

.action-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #FFFFFF;
	padding: 20rpx 40rpx 40rpx;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
	display: flex;
	gap: 20rpx;
}

.action-btn {
	flex: 1;
	border-radius: 50rpx;
	padding: 30rpx;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
}

.pay-btn {
	background-color: #D4AF37;
	color: #FFFFFF;
}

.pay-btn:active {
	background-color: #B8941F;
}

.cancel-btn {
	background-color: #FFFFFF;
	color: #666666;
	border: 2rpx solid #E0E0E0;
}

.cancel-btn:active {
	background-color: #F5F5F5;
}

.refund-btn {
	background-color: #FF8C00;
	color: #FFFFFF;
}

.refund-btn:active {
	background-color: #E07B00;
}

.confirm-btn {
	background-color: #52C41A;
	color: #FFFFFF;
}

.confirm-btn:active {
	background-color: #389E0D;
}

/* 无地址信息样式 */
.no-address {
	padding: 30rpx 20rpx;
	background-color: #F8F8F8;
	border: 2rpx dashed #E0E0E0;
	border-radius: 12rpx;
	text-align: center;
}

.no-address-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 12rpx;
}

.no-address-icon {
	font-size: 48rpx;
	margin-bottom: 8rpx;
}

.no-address-text {
	font-size: 28rpx;
	color: #666666;
	font-weight: bold;
}

.no-address-tip {
	font-size: 24rpx;
	color: #999999;
}
</style>
